<template>
    <!-- 饼状图 -->
  <div class='chart-wrap'>
    <div  ref="chartTraffic" class="chart-content" v-show="chatData?.length"></div>
    <el-empty description="暂无数据" v-show="!chatData?.length"/>
  </div>
</template>

<script setup>
  import * as echarts from 'echarts';
  import {getChartTrafficOption } from '../../echartOption'
  import { reactive } from 'vue';
  const props = defineProps({
    statisticData:{
      type:Array,
      default:()=>[]
    }
  })
  let chatData = reactive([])
  let chatDataX = reactive([])
  let dataYbBuss = reactive([])
  let dataYsBuss = reactive([])
  let echartsInstance = shallowRef(null);
  let chartTraffic = shallowRef();
  const initChart = ()=>{
    chatDataX = chatData?.map(ele => ele?.visitDate?.slice(5));
    dataYsBuss = chatData?.map(item => item.num1) || [];
    dataYbBuss = chatData?.map(item => item.num2) || [];
    echartsInstance.value = null;
    echartsInstance.value = echarts.init(chartTraffic.value, null, {renderer:'svg'})
    const option = getChartTrafficOption(chatDataX,dataYsBuss,dataYbBuss)
    echartsInstance.value.setOption(option,true)
    window.addEventListener('resize', resize);
  }

  const resize = () =>{
    if(!echartsInstance.value) return;
    echartsInstance.value?.resize()
  }

  const resetOption = () =>{
    // 指定图表的配置项和数据
    const option = getChartTrafficOption(chatDataX,dataYbBuss,dataYsBuss)
    // 使用刚指定的配置项和数据显示图表。
    if (!echartsInstance.value  && !echartsInstance.value ) {
      return
    }
    echartsInstance.value .setOption(option);
    const timer = setTimeout(() => {
      clearTimeout(timer)
      resize()
    }, 100);
  }

  onUnmounted(() => {
    // 组件卸载时销毁图表实例
    if(echartsInstance.value){
      echartsInstance.value.dispose();
    }
  });

  watch(() => props.statisticData,(newValue)=>{
    if(newValue?.length){
      chatData = newValue;
      nextTick(() => {
        initChart()
        resize()
      })
    }
    else{
      chatData = []
    }
  },
  {
    deep: true,
    immediate: true
  })
</script>
<style lang="scss" scoped>
  .chart-wrap{
    width: 30%;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
    .chart-content{
      width: 100%;
      height: 100%;
    }
  }
</style>
